import fs from 'fs'
const getJsFromHtml = (htmlFilePath) =>{
  // 使用fs读取html文件内容
  const htmlContent = fs.readFileSync(htmlFilePath, 'utf8');
  /**
   * htmlContent中有<link rel="modulepreload" href="/assets/login.html-Bdj1i3UK.js">内容，
   * 现在需要提取href中的/assets/login.html-Bdj1i3UK.js，正则中要包括/assets/login.html****.js
   */
  // 获取htmlFilePath的文件名
  const fileName = htmlFilePath.split('/').pop();
  const regex = new RegExp(`<link rel="modulepreload" href="(\/assets\/${fileName}-[^"]+)">`);
  const match = htmlContent.match(regex);
  if (match) {
    return match[1];
  }
  return "";
}
export const AuthPlugin = () =>{
  return {
    name: 'vuepress-auth-plugin',
    extendsPage(page){
      if(page.path == '/login.html') {
        // 给登录页设置环境变量
        page.data.GITEE_CLIENT_ID = process.env.GITEE_CLIENT_ID
        page.data.GITEE_REDIRECT_URI = process.env.GITEE_REDIRECT_URI
        // Login.vue中可以通过this.$page.GITEE_CLIENT_ID获取
      }
    },
    onGenerated(app){
      const needAuthUrls = []
      let loginJs = "";
      app.pages?.forEach(page=>{
        if(page.frontmatter.needAuth == true) {
          needAuthUrls.push(page.path)
          const jsPath = getJsFromHtml(page.htmlFilePath)
          if(jsPath) {
            needAuthUrls.push(jsPath)
          }
        }

        if(page.path == '/login.html') {
          // <link rel="modulepreload" href="/assets/login.html-Bdj1i3UK.js">
          const htmlFilePath = page.htmlFilePath;
          loginJs = getJsFromHtml(htmlFilePath)
        }
      })
      const configJson = {
        NEED_AUTH_URLS: needAuthUrls,
        LOGIN_JS : loginJs,
      }
      fs.writeFileSync(app.options.dest+'/config.json', JSON.stringify(configJson, null, 2))
    }
  }
}
export default AuthPlugin